package cn.diancan.action.manager;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ModelDriven;

import cn.diancan.action.BaseAction;
import cn.diancan.exception.OutMsgException;
import cn.diancan.manager.security.ManagerAuth;
import cn.diancan.model.Brand;
import cn.diancan.vo.manager.BrandManagerActionVo;
import cn.diancan.vo.other.Pager;

public class BrandAction extends BaseAction implements ModelDriven<BrandManagerActionVo> {

    private BrandManagerActionVo requestVo = new BrandManagerActionVo();

    private Pager pager = new Pager();

    //List
    @ManagerAuth
    public String brandListPage() {
        try {
            pager.setPageNumber(requestVo.getPageNumber());
            pager.setPageSize(10);
            brandService.findByPager(pager, requestVo.getBrandName());
            this.put("pager", pager);
            this.put("requestVo", requestVo);
            return freemarkView("/views/ftl/manager/brand/brand_list.ftl");
        } catch (OutMsgException e) {
            return managerError(e.getMessage());
        }
    }


    @ManagerAuth
    public String createBrandPage() {
        return freemarkView("/views/ftl/manager/brand/create_brand.ftl");
    }


    @ManagerAuth
    public String createBrand() {
        try {
            Brand brand = brandService.saveBrand(requestVo.getBrandName(), requestVo.getBrandLogo());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("brandId", brand.getId());
            jsonObject.put("brandName", brand.getBrandName());

            return jsonFormat(jsonObject, "添加成功", "添加失败");
        }   catch (Exception e) {
            return jsonError(e);
        }
    }


    @ManagerAuth
    public String brandInfo() {
        try {
            Brand brand = brandService.findBrandById(requestVo.getBrandId());
            this.put("brand", brand);
            return freemarkView("/views/ftl/manager/brand/brand_info.ftl");
        } catch ( Exception e) {
            return managerError(e.getMessage());
        }
    }


    @ManagerAuth
    public String modifyBrand() {
        try {
            Boolean result = brandService.updateBrand(requestVo.getBrandId(), requestVo.getBrandName(), requestVo.getBrandLogo());

            return jsonFormat(result, "修改成功", "修改失败");
        }  catch (Exception e) {
            return jsonError(e);
        }
    }


    @ManagerAuth
    public String removeBrand() {
        try {
            Boolean result = brandService.deleteBrandById(requestVo.getBrandId());
            return jsonFormat(result, "删除成功", "删除失败");
        } catch (Exception e) {
            return jsonError(e);
        }
    }


    @ManagerAuth
    public String brandList() {
        List<Brand> list = brandService.findList(requestVo.getPageNumber(), requestVo.getPageSize());
        return jsonFormat(list);
    }


    @Override
    public BrandManagerActionVo getModel() {
        return requestVo;
    }


}
